package com.talent.jiwen.my;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.CouponListResult;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;

public class CouponSelectActivity extends BaseActivity {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.noDataIv)
    ImageView noDataIv;
    @BindView(R.id.notUseTv)
    TextView notUseTv;

    private int startIndex = 1;
    private int useStatus = 0;
    private CommonAdapter<CouponListResult.Coupon> couponAdapter;
    private List<CouponListResult.Coupon> dataList = new ArrayList<>();
    public static final String REFRESH_COUPON_SELECT = "refresh.coupon.select";
    public static final String PARAM_COUPON_RESULT = "param.coupon.result";
    public static final String PARAM_SELECT_COUPON = "param.select.coupon";

    private CouponListResult.Coupon selectCoupon;

    private int idBindStatus = 0;////是否绑定身份证（0：未绑定 1：绑定）

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_coupon_select;
    }

    @Override
    public String titleName() {
        return "选择优惠券";
    }

    @Override
    protected void initData() {

        registEventBus();

        String selectConponStr = getIntent().getStringExtra(PARAM_SELECT_COUPON);
        if (!Validators.isEmpty(selectConponStr)){
            selectCoupon  = JSON.parseObject(selectConponStr , CouponListResult.Coupon.class);
        }

        noDataIv.setImageResource(R.mipmap.img_no_coupon);
        initRecycleView();

        notUseTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra(PARAM_COUPON_RESULT, "");
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    @Subscribe
    public void onEvent(String flag){
        if (flag.equals(REFRESH_COUPON_SELECT)){
            refreshLayout.autoRefresh();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
    }

    /**初始化recycleView
     *
     */
    private void initRecycleView(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        couponAdapter = new CommonAdapter<CouponListResult.Coupon>(this, R.layout.item_coupon_no_use, dataList) {
            @Override
            protected void convert(ViewHolder holder, final CouponListResult.Coupon coupon, int position) {
                RelativeLayout rootLayout = holder.getView(R.id.rootLayout);
                TextView moneyTv = holder.getView(R.id.moneyTv);
                TextView desTv = holder.getView(R.id.desTv);
                TextView couponNameTv = holder.getView(R.id.couponNameTv);
                TextView useTimeTv = holder.getView(R.id.useTimeTv);
                TextView optionTv = holder.getView(R.id.optionTv);
                ImageView flagIv = holder.getView(R.id.flagIv);
                ImageView selectIv = holder.getView(R.id.selectIv);

                moneyTv.setText("¥" + coupon.getDiscountAmount());
                desTv.setText(coupon.getDiscountName());
                couponNameTv.setText(coupon.getCouponName());

                long startTime = coupon.getCreateTime();
                long endTime = coupon.getCreateTime() + coupon.getValidTime() * 24 * 60 *60 *1000;
                useTimeTv.setText("(" + ms2DateWithPoint(startTime) + "-" + ms2DateWithPoint(endTime) + ")");

                rootLayout.setBackgroundResource(R.mipmap.bg_coupon_normal);

                optionTv.setVisibility(View.GONE);
                flagIv.setVisibility(View.GONE);
                selectIv.setVisibility(View.VISIBLE);

                if (coupon.isSelsect()){
                    selectIv.setImageResource(R.mipmap.img_choose);
                }else{
                    selectIv.setImageResource(R.mipmap.img_no_chooae);
                }

                rootLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (idBindStatus == 0){
                            intentActivity(CardBindActivity.class);
                        }else{

                            Intent intent = new Intent();
                            intent.putExtra(PARAM_COUPON_RESULT, JSON.toJSONString(coupon));
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    }
                });
            }
        };
        recyclerView.setAdapter(couponAdapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                startIndex = 1;
                getCouponList();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                startIndex ++ ;
                getCouponList();
            }
        });

        refreshLayout.autoRefresh();
    }

    /**
     * 获取优惠券列表
     */
    private void getCouponList() {
        Map<String, String> map = new HashMap<>();
        map.put("useStatus", useStatus + "");
        map.put("startIndex", startIndex + "");

        Observable observable = ApiFactory.getEducationApiSingleton().getCouponList(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<CouponListResult>(this) {
            @Override
            protected void _onNext(CouponListResult result) {
                idBindStatus = result.getIDNoBindStatus();
                if(startIndex == 1){
                    dataList.clear();
                    dataList.addAll(result.getCouponList());
                    refreshLayout.finishRefresh();
                }else{
                    dataList.addAll(result.getCouponList());
                    refreshLayout.finishLoadMore();

                    if (result.getCouponList().size() < 10){
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }

                if (null != selectCoupon){
                    for(CouponListResult.Coupon coupon : dataList){
                        if(coupon.getId() == selectCoupon.getId()){
                            coupon.setSelsect(true);
                        }else{
                            coupon.setSelsect(false);
                        }
                    }
                }
//                if (!Validators.isEmpty(dataList)){
//                    if (null != selectCoupon){
//                        dataList.get(0).setSelsect(true);
//                    }
//                }
                couponAdapter.notifyDataSetChanged();

                if (Validators.isEmpty(dataList)){
                    if(noDataIv!=null){
                        noDataIv.setVisibility(View.VISIBLE);
                    }

                }else{
                    if(noDataIv!=null){
                        noDataIv.setVisibility(View.GONE);
                    }
                }

            }

            @Override
            protected void _onError(String message) {
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                }
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);
    }


    /**时间转换
     *
     * @param _ms
     * @return
     */
    private static String ms2DateWithPoint(long _ms){
        Date date = new Date(_ms);
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault());
        return format.format(date);
    }
}
